#include "player.hpp"

namespace Server
{
	// `extern' enables external linking for constants which is disabled at default
	extern const short unitsToEnergy[]   = {0, 0, 1, 1,  2,  3,  5,  7,  9, 12,  20};
	extern const short unitsToVelocity[] = {0, 3, 6, 8, 12, 15, 20, 30, 40, 60, 120};


	short vectorModulo(short x, short y)
	{
		return abs(x) + abs(y);
	}

	bool Player::adjustVelocity(short x, short y)
	{
		velx += x;
		vely += y;
		return Server::vectorModulo(velx, vely) <= getMaxVelocity();
	}

	bool Player::adjustDurability(short value)
	{
		if (durability += value <= 0) {
			kill();
			return false;
		}
		else
			return true;
	}

	void Player::adjustEnergy(short value)
	{
		energy += value;
		if (energy > maxEnergy)
			energy = maxEnergy;
	}
	
	void Player::brake()
	{
		velx = 0;
		vely = 0;
	}
	
	bool Player::isCouldShoot(short tx, short ty)
	{
		if (vectorModulo(x - tx, y - ty) > shootSector)
			return false;
		if (velocityModulo() == 0)
			return true;

		// a bunch of $%^& calculations
		static const float cos_pi8_squared = 0.85355339059327376220042218105242f; // (cos(pi/8))^2

		float x1 = velx, y1 = vely;
		float x2 = tx - x, y2 = ty - y;
		float dotProduct = x1*x2 + y1*y2;

		return dotProduct*dotProduct > (x1*x1 + y1*y1)*(x2*x2 + y2*y2)*cos_pi8_squared;
	}


}
